var common = require('../../utils/common.js');
var ajax = require('../../utils/ajax.js');
var Base = require('../../common/CmptBase.js');

var PAGE_SIZE = 10;

var Pagination = function({
  page,
  scope,
}) {
  Base.apply(this, arguments);
}

common.extend(Pagination, Base);

Object.assign(Pagination.prototype, {
  /**
   * 组件初始化，需要手动调用传参
   * @param  {Object} optinos [description]
   * @return {[type]}         [description]
   */
  init(optinos = {}) {
    var {
      defaultPage = 1
    } = optinos;
    
    this._options = optinos;

    this.setData({
      currentPage: defaultPage,
      pageLoading: false,
      pageEnd: false,
    });

    this._loadPage();
    return this;
  },

  /**
   * 加载下一页
   * @return {[type]} [description]
   */
  loadNext() {
    if (this.getData('pageEnd')) {
      return true;
    }
    this._loadPage();
  },

  /**
   * 刷新分页组件
   * @return {[type]} [description]
   */
  flush(cb) {
    var {
      defaultPage = 1
    } = this._options;

    this.setData({
      currentPage: defaultPage
    });
    this._loadPage(cb);
  },

  /**
   * 加载页面数据
   * @return {[type]} [description]
   */
  _loadPage(cb) {
    var {
      rendData: rendDataFunc
    } = this._options;
    var currentPage = this.getData('currentPage');

    this.setData({
      pageLoading: true
    });
    rendDataFunc && rendDataFunc(currentPage, (dataSize) => {

      this.setData({
        currentPage: currentPage + 1,
        pageLoading: false,
        pageEnd: dataSize < PAGE_SIZE,
      });

      cb && cb();

    })
  },

});

module.exports = Pagination;